package cn.dansj.configure;

import cn.dansj.bean.CurrentThreadLocalUserInfo;
import cn.dansj.common.utils.bean.CacheToken;
import cn.dansj.entity.RoleMenu;
import cn.dansj.enums.GlobalEnv;
import cn.dansj.service.RoleMenuService;
import cn.dansj.utils.project.ProjectUtils;
import com.xxl.job.configure.XxlJobConfiguration;
import com.xxl.job.entity.XxlJobInfo;
import org.springframework.context.annotation.Configuration;
import com.xxl.job.glue.GlueTypeEnum;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class XxlJobConfig implements XxlJobConfiguration {
    private final RoleMenuService roleMenuService;

    public XxlJobConfig(RoleMenuService roleMenuService) {
        this.roleMenuService = roleMenuService;
    }

    @Override
    public boolean isAdministrator() {
        final CacheToken cacheToken = CurrentThreadLocalUserInfo.getCurrentThreadLocalUserInfo().getCacheToken();
        return GlobalEnv.Admin.equals(cacheToken.getUsername()) || GlobalEnv.SuperAdmin.equals(cacheToken.getRole());
    }

    @Override
    public List<String> allowTasks() {
        final CacheToken cacheToken = CurrentThreadLocalUserInfo.getCurrentThreadLocalUserInfo().getCacheToken();
        List<RoleMenu> roleMenuList = roleMenuService.getAllByRole(cacheToken.getRole());
        final List<String> task = GlueTypeEnum.getJobType().stream().map(e -> "/task/" + e.toLowerCase()).toList();
        List<String> glueTypes = new ArrayList<>();
        for (RoleMenu roleMenu : roleMenuList) {
            if (task.contains(roleMenu.getSubMenu())) {
                glueTypes.add(GlueTypeEnum.match(roleMenu.getSubMenu().split("/")[2]).name());
            }
        }
        return glueTypes;
    }

    @Override
    public void backupXxlJobInfo(XxlJobInfo xxlJobInfo) {
        ProjectUtils.backUpTask(xxlJobInfo);
    }
}
